package dtm

import (
	"context"
	"database/sql"

	// "fmt"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/dtm-labs/client/dtmgrpc"
	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/logx"
)

type ExchangeCouponRevertLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewExchangeCouponRevertLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExchangeCouponRevertLogic {
	return &ExchangeCouponRevertLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ExchangeCouponRevertLogic) ExchangeCouponRevert(in *promotion.CouponInfo) (*promotion.BaseResp, error) {
	// logrus.Info(fmt.Sprintf("ExchangeCouponRevert: %+v", in))
	logx.Infof("ExchangeCouponRaw: %+v ", in)

	if in.TemplateId == nil || *in.TemplateId == 0 {
		return nil, resultx.StatusError(resultx.COUPON_ID_REQUIRED, "")
	}

	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	if in.StartedAt == nil || in.EndedAt == nil || len(*in.StartedAt) == 0 || len(*in.EndedAt) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	var startedAt time.Time
	if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
		startedAt = localTime
	} else {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	var endedAt time.Time
	if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
		endedAt = localTime
	} else {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	// 获取子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, resultx.StatusError(resultx.DTM_ERROR, err.Error())
	}

	// 开启子事务屏障
	err = barrier.CallWithDB(l.svcCtx.DB, func(tx *sql.Tx) error {
		var mods []qm.QueryMod
		mods = append(mods, model.PromotionCouponWhere.TemplateID.EQ(*in.TemplateId))
		mods = append(mods, model.PromotionCouponWhere.UserID.EQ(*in.UserId))
		if in.ActivityId != nil && *in.ActivityId > 0 {
			mods = append(mods, model.PromotionCouponWhere.ActivityID.EQ(*in.ActivityId))
		}
		mods = append(mods, model.PromotionCouponWhere.Status.EQ(uint16(globalkey.StatusStarted)))
		mods = append(mods, model.PromotionCouponWhere.StartedAt.EQ(null.TimeFrom(startedAt)))
		mods = append(mods, model.PromotionCouponWhere.EndedAt.EQ(null.TimeFrom(endedAt)))
		mods = append(mods, qm.OrderBy(model.PromotionCouponColumns.CouponID+" DESC"))
		mods = append(mods, qm.Limit(int(1)))
		_, err = model.PromotionCoupons(mods...).UpdateAll(l.ctx, tx, model.M{
			model.PromotionCouponColumns.Status: uint8(globalkey.StatusExpired),
		})
		if err != nil {
			logx.Errorw("ExchangeCouponRevert Update err", logx.Field("detail", err.Error()))
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &promotion.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
